package com.huaqin.punan;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.telephony.NeighboringCellInfo;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
	public static final String TAG = "PunanGetLocationMain";
	
	private Button btn1;
	private Button btn2;
	private Button btn3;
	private Button btn4;
	private TextView tv1;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		btn1 = (Button)findViewById(R.id.btn1);
		btn2 = (Button)findViewById(R.id.btn2);
		btn3 = (Button)findViewById(R.id.btn3);
		btn4 = (Button)findViewById(R.id.btn4);
		tv1 = (TextView)findViewById(R.id.tv1);
		
		btn1.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				requestGPSLocation();
			}});
		btn2.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				requestTelLocation();
			}});
		btn3.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				requestWIFILocation();
			}});
		btn4.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				requestNetworkLocation();
			}});
				
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}
	
	
    private void requestTelLocation() {
        TelephonyManager mTelMan = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        // MCC+MNC. Unreliable on CDMA networks
        String operator = mTelMan.getNetworkOperator();
        String mcc = operator.substring(0, 3);
        String mnc = operator.substring(3);
 
        GsmCellLocation location = (GsmCellLocation) mTelMan.getCellLocation();
        int cid = location.getCid();
        int lac = location.getLac();
 
        JSONObject tower = new JSONObject();
        try {
            tower.put("cell_id", cid);
            tower.put("location_area_code", lac);
            tower.put("mobile_country_code", mcc);
            tower.put("mobile_network_code", mnc);
        } catch (JSONException e) {
            Log.e(TAG, "call JSONObject's put failed", e);
        }
 
        JSONArray array = new JSONArray();
        array.put(tower);
 
        List<NeighboringCellInfo> list = mTelMan.getNeighboringCellInfo();
        Iterator<NeighboringCellInfo> iter = list.iterator();
        NeighboringCellInfo cellInfo;
        JSONObject tempTower;
        while (iter.hasNext()) {
            cellInfo = iter.next();
            tempTower = new JSONObject();
            try {
                tempTower.put("cell_id", cellInfo.getCid());
                tempTower.put("location_area_code", cellInfo.getLac());
                tempTower.put("mobile_country_code", mcc);
                tempTower.put("mobile_network_code", mnc);
            } catch (JSONException e) {
                Log.e(TAG, "call JSONObject's put failed", e);
            }
            array.put(tempTower);
        }
 
        JSONObject object = createJSONObject("cell_towers", array);
        requestLocation(object);
    }
    
    private void requestWIFILocation() {
        WifiManager wifiMan = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifiMan.getConnectionInfo();
        String mac = info.getMacAddress();
        String ssid = info.getSSID();
 
        JSONObject wifi = new JSONObject();
        try {
            wifi.put("mac_address", mac);
            wifi.put("ssid", ssid);
        } catch (JSONException e) {
            e.printStackTrace();
        }
 
        JSONArray array = new JSONArray();
        array.put(wifi);
 
        JSONObject object = createJSONObject("wifi_towers", array);
        requestLocation(object);
    }
    
    private void requestLocation(JSONObject object) {
        Log.d(TAG, "requestLocation: " + object.toString());
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://www.google.com/loc/json");
        try {
            StringEntity entity = new StringEntity(object.toString());
            post.setEntity(entity);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
 
        try {
            HttpResponse resp = client.execute(post);
            HttpEntity entity = resp.getEntity();
            BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
            StringBuffer buffer = new StringBuffer();
            String result = br.readLine();
            while (result != null) {
                buffer.append(result);
                result = br.readLine();
            }
            tv1.setText(buffer.toString());
            Log.d(TAG, buffer.toString());
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    private JSONObject createJSONObject(String arrayName, JSONArray array) {
        JSONObject object = new JSONObject();
        try {
            object.put("version", "1.1.0");
            object.put("host", "maps.google.com");
            object.put(arrayName, array);
        } catch (JSONException e) {
            Log.e(TAG, "call JSONObject's put failed", e);
        }
        return object;
    }
    
    private void requestGPSLocation() {
        LocationManager mLocMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        mLocMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000 * 60, 100, mLocLis);
    }
    
    private void requestNetworkLocation() {
        LocationManager mLocMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        mLocMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000 * 60, 100, mLocLis);
    }
    
    private LocationListener mLocLis = new LocationListener() {
    	 
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            Log.d(TAG, "onStatusChanged, provider = " + provider);
        }
 
        @Override
        public void onProviderEnabled(String provider) {
            Log.d(TAG, "onProviderEnabled, provider = " + provider);
        }
 
        @Override
        public void onProviderDisabled(String provider) {
            Log.d(TAG, "onProviderDisabled, provider = " + provider);
        }
 
        @Override
        public void onLocationChanged(Location location) {
            double latitude = location.getLatitude();
            double longitude = location.getLongitude();
            tv1.setText("latitude: " + latitude + ", longitude: " + longitude);
            Log.d(TAG, "latitude: " + latitude + ", longitude: " + longitude);
        }
    };
	
}
